package api

import (
	"fmt"
	"net/http"
	"time"

	"gitee.com/go-course/go11/devcloud-mini/cmdb/apps/secret"
	"gitee.com/go-course/go11/devcloud-mini/cmdb/tracer"
	"gitee.com/go-course/go11/devcloud-mini/mcenter/apps/token"
	"github.com/emicklei/go-restful/v3"
	"github.com/gorilla/websocket"

	"github.com/infraboard/mcube/http/restful/response"
)

// GoRestful Handler 需要符合框架签名
func (h *Handler) QuerySecret(r *restful.Request, w *restful.Response) {
	// 获取请求上下文
	tk := r.Attribute(token.CONTEXT_ATTRIBUTE_KEY)

	// 添加一个Trace的自定义埋点
	ctx, span := tracer.Tracer.Start(r.Request.Context(), "QuerySecret")
	defer span.End()

	// 后续的Ctx 必须使用新的Ctx
	fmt.Println(ctx)

	// 根据用户信息来编写业务逻辑

	// 用隐式接口 Desense() 来完成自动脱敏
	fmt.Println(tk)
	response.Success(w, tk)
}

var (
	upgrader = websocket.Upgrader{
		HandshakeTimeout: 60 * time.Second,
		ReadBufferSize:   8192,
		WriteBufferSize:  8192,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

// GoRestful Handler 需要符合框架签名
func (h *Handler) SyncResource(r *restful.Request, w *restful.Response) {
	ws, err := upgrader.Upgrade(w, r.Request, nil)
	if err != nil {
		fmt.Println(err)
		response.Failed(w, err)
		return
	}

	// 获取请求上下文
	// 不要使用中间件来做任务: 如果认证失败了 客户端获取不到失败原因
	// 先建立socket, 在socket里面进行认证
	// ws.WriteMessage("校验成功/xxxxx")

	// 根据用户信息来编写业务逻辑
	// 需要一个webscoket 来 send response
	// 需要把 websocket 封装成 secret.Rpc_SyncResourceServer
	term := NewSyncResourceTerminal(ws)
	req := &secret.SyncResourceRequest{
		SecretId: r.PathParameter("id"),
	}

	err = h.svc.SyncResource(req, term)
	if err != nil {
		fmt.Println(err)
	}
}
